﻿using Core.Configuration.Helper;
using Core.Configuration.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Net;

namespace Core.Configuration.Startup
{
    /// <summary>
    /// asp.net Core 环境全局异常
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            var status = HttpStatusCode.InternalServerError;
            var result = new ApiResult()
            {
                status = (int)status,
                message = context.Exception.Message,
                data = context.Exception.ToString()
            };
            var url = WebHelper.GetRequestUri(context.HttpContext.Request);
            var body = WebHelper.GetRequestBody(context.HttpContext.Request);
            LogHelper.WriteLog("err", $"{url}\r\npost:\r\n{body}\r\n{result.ToString()}");

            context.Result = new ObjectResult(result);
        }
    }

    /// <summary>
    /// 自定义的业务异常
    /// </summary>
    public class BusinessException : Exception
    {
        private string error;
        public BusinessException(string message) : base(message)
        {
            error = message;
        }
    }
}